
var directions = {
   'n': [0, -1],
   's': [0, 1],
   'w': [-1, 0],
   'e': [1, 0],
   'nw': [-1, -1],
   'ne': [1, -1],
   'sw': [-1, 1],
   'se': [1, 1],
};

/**
 * Animated Sprite
 *
 * @param {Object} animations
 * @param {fps} Frames Per Second for animations
 * @param {spritesPath} root path for sprites
 */
var AnimatedSprite = exports.AnimatedSprite = function(pos, params) {
   gamejs.extra.iso.AnimatedSprite.superConstructor.apply(this, []);
   
   var animations = params.names;
   var fps = params.fps;
   var spritesPath = params.rootPath.substr(2);
   
   var animation = 'stopped';
   var animationStep = 0;
   var animationDirection = 's';
   var movementSpeed = params.movementSpeed;
   var lastAnimationTime= null;
      
   this.image = new gamejs.Surface([96, 96]);
   this.image.fill("#ff0000");
   this.rect = this.image.getRect();
   var center = this.rect.center = pos;

   this.setAnimation = function(newAnimation) {
      // FIXME check if valid animation
      animation = newAnimation;
      animationStep = 0;
      return;
   };

   this.setDirection = function(newDirection) {
      // FIXME check if valid direction
      animationDirection = newDirection;
      return;
   }

   this.update = function(msDuration) {
      var now = Date.now();
      if (lastAnimationTime === null || now - lastAnimationTime > 1000/fps) {
         animationStep++;
         lastAnimationTime = now;
      }
      if (animationStep >= animations[animation]) {
         animationStep = 0;
      }
      
      this.image = gamejs.image.load(
         getImagePath(spritesPath, animation, animationDirection, animationStep)
      );
      
      if (animation == 'walking') {
         var speed = animationDirection.length > 1 ? movementSpeed / 2 : movementSpeed;
         
         center[0] += directions[animationDirection][0] * speed;
         center[1] += directions[animationDirection][1] * speed;
      }
      
      this.rect = this.image.getRect();
      this.rect.center = center;
      
      return;
   };
      
   return this;
};
gamejs.util.extend(AnimatedSprite, gamejs.sprite.Sprite);

function getImagePath(root, animation, direction, step) {
   return root + animation.replace(' ', '%20') + '%20' + direction + formatStep(step) + '.png';
}

function formatStep(step) {
   step = step.toString();
   while (step.length < 4) {
      step = "0" + step;
   }
   return step;
};

var preload = exports.preload = function(params) {
   var rootPath = params.rootPath;
   var animations = params.names;
   var images = [];
   for (var animationName in animations) {
      for (var i=0; i < animations[animationName]; i++) {
         for (var directionName in directions) {
            images.push(getImagePath(rootPath, animationName, directionName, i));
         }
      }
   }
   gamejs.image.preload(images);
   return;
};


